package com.listen.playanddown;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.listen.playanddown.api.RequestApi;
import com.listen.playanddown.bean.MusicBean;
import com.listen.playanddown.bean.PlayClick;
import com.wgl.android.library.base.BaseActivity;
import com.wgl.android.library.baserx.RxSchedulers;
import com.wgl.android.library.baserx.RxSubscriber;
import com.wgl.android.library.commonutils.LogUtils;
import com.wgl.android.library.commonwidget.CircleImageView;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import rx.android.schedulers.AndroidSchedulers;

public class MainActivity extends BaseActivity {
    @Bind(R.id.recycler_view)
    XRecyclerView recycler;
    private List<MusicBean.MsgEntity.DataEntity> data;
    private int page = 1;


    @Override
    public int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    protected void initView() {
        initDate();
        registerReceiver(receiver, new IntentFilter("com.hzjm.notifi"));

    }

//    private Subscription mSubscription;


    private BroadcastReceiver receiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            switch (intent.getIntExtra("action", 0)) {
                case 0:
                    mRxManager.post("notifi", new PlayClick(0));
                    break;
                case 1:
                    mRxManager.post("notifi", new PlayClick(1));
                    break;
            }
        }
    };

    @Override
    protected void onDestroy() {
        if (receiver != null) {
            unregisterReceiver(receiver);
        }
        super.onDestroy();
    }

    private void initDate() {
        data = new ArrayList<>();
        recycler.setLayoutManager(new LinearLayoutManager(MainActivity.this, LinearLayoutManager.VERTICAL, false));
        recycler.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                page = 1;
                loadData(true);
            }

            @Override
            public void onLoadMore() {
                ++page;
                loadData(false);
            }
        });

        adapter = new MyAdapter(data);
        recycler.setAdapter(adapter);
        recycler.refresh();
        recycler.setLoadingMoreProgressStyle(2);
    }

    private void loadData(final boolean isRefresh) {
        RequestApi.getInstance().getApiService().getMusic(page + "")
                .compose(RxSchedulers.<MusicBean>io_main())
                .observeOn(AndroidSchedulers.mainThread())  //回到主线程去处理结果
                .subscribe(new RxSubscriber<MusicBean>(MainActivity.this) {
                    @Override
                    protected void _onNext(MusicBean bean) {
                        if (isRefresh) data.clear();
                        data.addAll(bean.getMsg().getData());
                        adapter.notifyDataSetChanged();
                        recycler.refreshComplete();
                    }

                    @Override
                    protected void _onError(String message) {
                        LogUtils.loge(message);
                        if (!isRefresh) {
                            recycler.setNoMore(true);
                            adapter.notifyDataSetChanged();
                            showShortToast("没有更多了");
                        } else {
                            recycler.refreshComplete();
                            showShortToast(message + "");
                        }
                    }
                });
    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            View view = View.inflate(this, R.layout.dialog_exit, null);
            builder.setView(view);
            final AlertDialog show = builder.show();
            view.findViewById(R.id.no).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    show.cancel();
                }
            });
            view.findViewById(R.id.yes).setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    System.exit(0);
                    overridePendingTransition(R.anim.fade_in,
                            R.anim.fade_out);
                }
            });
            view.findViewById(R.id.homes).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    show.cancel();
                    moveTaskToBack(false);
                }
            });
            return super.onKeyDown(keyCode, event);
        } else
            return super.onKeyDown(keyCode, event);
    }

    MyAdapter adapter;

    class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
        public List<MusicBean.MsgEntity.DataEntity> datas = null;

        public MyAdapter(List<MusicBean.MsgEntity.DataEntity> datas) {
            this.datas = datas;
        }

        //创建新View，被LayoutManager所调用
        @Override
        public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
            View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_gefragment, viewGroup, false);
            return new ViewHolder(view);
        }

        //将数据与界面进行绑定的操作
        @Override
        public void onBindViewHolder(ViewHolder viewHolder, final int position) {
            Glide.with(MainActivity.this).load(datas.get(position).getThumbnail())
                    .into(viewHolder.iv);
            viewHolder.author.setText(datas.get(position).getMp3_duration());
            viewHolder.name.setText(datas.get(position).getTitle());
            viewHolder.ll_max.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Application.setData(datas);
                    startActivity(new Intent(MainActivity.this, PlayActivity.class).putExtra("position", position));
                }
            });


        }

        //获取数据的数量
        @Override
        public int getItemCount() {
            return datas.size();
        }

        //自定义的ViewHolder，持有每个Item的的所有界面元素
        class ViewHolder extends RecyclerView.ViewHolder {
            public TextView name, author;
            public CircleImageView iv;
            LinearLayout ll_max;
            TextView state;

            public ViewHolder(View view) {
                super(view);
                name = (TextView) view.findViewById(R.id.name);
                author = (TextView) view.findViewById(R.id.author);
                iv = (CircleImageView) view.findViewById(R.id.img);
                ll_max = (LinearLayout) view.findViewById(R.id.ll_max);
                state = (TextView) view.findViewById(R.id.state);
            }
        }
    }
}
